package com.inno.log.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.inno.log.entity.OperationLog;
import com.inno.log.dao.OperationLogDao;
import com.inno.log.entity.OperationLogVO;
import com.inno.log.entity.PageResult;
import com.inno.log.service.OperationLogService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * (OperationLog)表服务实现类
 *
 * @author makejava
 * @since 2025-01-20 11:45:26
 */
@Service("operationLogService")
public class OperationLogServiceImpl implements OperationLogService {
    @Resource
    private OperationLogDao operationLogDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OperationLog queryById(Long id) {
        return this.operationLogDao.queryById(id);
    }



    /**
     * 新增数据
     *
     * @param operationLog 实例对象
     * @return 实例对象
     */
    @Override
    public OperationLog insert(OperationLog operationLog) {
        this.operationLogDao.insert(operationLog);
        return operationLog;
    }

    /**
     * 修改数据
     *
     * @param operationLog 实例对象
     * @return 实例对象
     */
    @Override
    public OperationLog update(OperationLog operationLog) {
        this.operationLogDao.update(operationLog);
        return this.queryById(operationLog.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.operationLogDao.deleteById(id) > 0;
    }

    @Override
    public PageResult<OperationLogVO> queryPage(OperationLog operationLog) {
        PageHelper.startPage(operationLog.getPage(), operationLog.getPageSize());
        Page<OperationLog> entityPage = this.operationLogDao.queryPage(operationLog);

        return PageResult.of(convertEntityListToVOList(entityPage.getResult()),entityPage.getTotal());
    }

    private static List<OperationLogVO> convertEntityListToVOList(List<OperationLog> entityList){
        List<OperationLogVO> result = new ArrayList<>();
        for (OperationLog entity : entityList) {
            OperationLogVO operationLogVO = new OperationLogVO();
            BeanUtil.copyProperties(entity, operationLogVO);
            String operationEquipment = entity.getOperationEquipment();
            if (StringUtils.isNotBlank(operationEquipment)){
                String[] arr = operationEquipment.split(":");
                operationLogVO.setClientType(arr[0]);
                operationLogVO.setOs(arr[1]);
                operationLogVO.setBrowser(arr[2]);
            }
            result.add(operationLogVO);
        }
        return result;
    }
}
